package feces.filter;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import feces.formater.IFormater;
import feces.formater.JSONFormater;
import feces.utility.IO;

/**
 * JSON请求过滤器
 *
 * @author Bromine0x23
 */
@WebFilter(filterName = "json_filter", urlPatterns = "*.json")
public class JSONFilter implements Filter {
	
	private Pattern pattern;

	@Override
	public void init(FilterConfig config) throws ServletException {
		pattern = Pattern.compile(
			IO.sprintf("^%s(.+)\\.json$", config.getServletContext().getContextPath())
		);
	}

	@Override
	public void doFilter(
		ServletRequest request,
		ServletResponse response,
		FilterChain chain
	) throws IOException, ServletException {
		boolean forward = false;
		if (request instanceof HttpServletRequest) {
			String uri = ((HttpServletRequest) request).getRequestURI();
			Matcher matcher = pattern.matcher(uri);
			if (matcher.matches()) {
				RequestDispatcher dispatcher = request.getRequestDispatcher(matcher.group(1));
				request.setAttribute(IFormater.KEY_FORMAT, new JSONFormater());
				response.setContentType("text/json");
				dispatcher.forward(request, response);
				forward = true;
			}
		}
		if (!forward) {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void destroy() {
		// do nothing
	}

}
